package com.sto.stoapp.activity.aviation.jipaoqi;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

public class MeasureArrivePieceBeforeActivity extends StoListenerActivity {
	private static byte[] preCommand = { 0x40, 0x02, 0x4F, 0x03, 0x52, 0x2A };
	private static byte[] scanCommand = { 0x40, 0x02, 0x4F, 0x01, 0x52, 0x2A };

	private BearingBlueThread bearingBlueThread;
	private OutputStream os;
	private InputStream is;

	private Handler sendHandler;

	private static int SEND_SCAN_COMMAND = 0x44;
	public static final int BLUETOOTH_DATA_WHTA = 0x14;
	private boolean isFinish = false;
	private int[] companyMachCode = null;
	private String machineCode;
	private final int COURIER_RESULT = 0xfe;
	private DataBusinessEntity dataBusiness;
	StoHhmEditText code;
	TextView lenghtTV, wideTV, volumeTV, highTV, weightTV;
	String decimalPlaces;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.weight_arrive_piece_scan);
		this.setTitleBottom("轻泡货到件", HomeBroadAction.AVIATION_SCANNER_BROAD);
		initView();
		initListen();
		initPointLayout(true);
		initScanRecordAdapter(
				EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE, true);

		initScanListener();
		addUploadTable(EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE);
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		decimalPlaces = StoFilePreference.getInstance(this)
				.getSelectedDecimalPlacesControl();

	}

	private void initView() {
		code = (StoHhmEditText) findViewById(R.id.sanning_code);
		lenghtTV = (TextView) findViewById(R.id.lenght);
		wideTV = (TextView) findViewById(R.id.wide);

		volumeTV = (TextView) findViewById(R.id.volume);
		highTV = (TextView) findViewById(R.id.height);
		weightTV = (TextView) findViewById(R.id.weight);
	}

	private void initListen() {


		// 单号
		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
			}

			@Override
			public void onEditClickListener(View v) {
				onScanResults(code.getText().toString());
			}
		});
	}





	Handler jHandler = new Handler(new Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case BearingBlueThread.BLUETOOTH_NO_SETUP: // 蓝牙未设置
				bearingBlueThread.cancelDialog();
				weightTV.setText("蓝牙未设置");

				break;
			case BearingBlueThread.CONNECT_START: // 开始连接
				Helper.showToast(MeasureArrivePieceBeforeActivity.this,
						"开始连接蓝牙");
				bearingBlueThread.showDialogByMessage("正在连接蓝牙");
				break;
			case BearingBlueThread.BLUETOOTH_CONNECTION_ERROR: // 蓝牙连接失败
				bearingBlueThread.cancelDialog();
				weightTV.setText("蓝牙连接失败");
				Helper.showToast(MeasureArrivePieceBeforeActivity.this,
						"蓝牙连接失败");
				break;
			case BearingBlueThread.CONNECT_OBJ: // 获取蓝牙socket
				if (msg.obj != null) {
					BluetoothSocket socket = (BluetoothSocket) msg.obj;
					try {
						os = socket.getOutputStream();
						is = socket.getInputStream();
						Helper.showToast(MeasureArrivePieceBeforeActivity.this,
								"蓝牙连接成功");
						weightTV.setText("蓝牙连接成功");
						new ReadThread(MeasureArrivePieceBeforeActivity.this)
								.start();
					} catch (IOException e) {
						bearingBlueThread.cancelDialog();
						Helper.showToast(MeasureArrivePieceBeforeActivity.this,
								"获取输入输出流异常");
						e.printStackTrace();
					}
				} else {
					weightTV.setText("蓝牙连接失败");
					Helper.showToast(MeasureArrivePieceBeforeActivity.this,
							"蓝牙连接失败");
				}
				bearingBlueThread.cancelDialog();
				break;
			case BLUETOOTH_DATA_WHTA: // 获取蓝牙数据

				JipaoqiDataEntity data = (JipaoqiDataEntity) msg.obj;
				dealBlueData(data);
				code.setEnabled(true);

				break;

			default:
				break;
			}
			return false;
		}
	});

	@Override
	protected void onResume() {
		super.onResume();
		if (bearingBlueThread == null) {
			bearingBlueThread = new BearingBlueThread(this, jHandler);
			bearingBlueThread.start();
		}
	}

	private void dealBlueData(JipaoqiDataEntity data) {
		try {
			if (Float.parseFloat(data.weight) > 0 && data.volume > 0) {
				lenghtTV.setText(data.lenght + "");
				wideTV.setText(data.wide + "");
				highTV.setText(data.high + "");
				weightTV.setText(data.weight);
				volumeTV.setText(data.volume + "");
				if (TextUtils.isEmpty(code.getText().toString())) {
					Helper.showSoundToast(this, getString(R.string.code_empty),
							false);
				} else {
					doSave(data);
				}
			} else {
				Helper.showSoundToast(this, "重量体积数据必须大于0", false);
			}
		} catch (Exception e) {

			e.printStackTrace();
			Helper.showSoundToast(this, "数据解析有误", false);
		}
		ScanOpen();
	}

	private String codeNum = "";

	private void sendCommand() {
		if (sendHandler != null) {
			codeNum = code.getText().toString();
			sendHandler.sendEmptyMessage(SEND_SCAN_COMMAND);	
			code.setEnabled(false);
			lenghtTV.setText("");
			wideTV.setText("");
			highTV.setText("");
			weightTV.setText("");
			volumeTV.setText("");
		}
	}

	@SuppressLint("HandlerLeak")
	class SendCommandThread extends Thread {

		@Override
		public void run() {
			super.run();
			Looper.prepare();
			sendHandler = new Handler() {

				@Override
				public void handleMessage(Message msg) {
					super.handleMessage(msg);
					if (msg.what == SEND_SCAN_COMMAND) {
						try {

							os.write(getCommand(codeNum));
							os.flush();
						} catch (IOException e) {
							ExceptionLog
									.writeLog(
											"MeasureArrivePieceBeforeActivity SendCommandThread.sendHandler巴枪扫描单号后向动态秤发送命令",
											e.getMessage());
							e.printStackTrace();
						}
					}
				}
			};
			Looper.loop();
		}

		private byte[] getCommand(String randomCode) {
		//	randomCode=Helper.getStringFromDate(new Date(), "yyyyMMdd")+randomCode;
			int length = randomCode.length();
			byte[] bs = new byte[length + 2];
			bs[0] = 0x02;
			bs[length + 1] = 0x03;
			byte[] codeBytes = randomCode.getBytes();
			for (int i = 0; i < length; i++) {
				bs[i + 1] = codeBytes[i];
			}
			return bs;
		}

	}

	class ReadThread extends Thread {
		private Context context;

		public ReadThread(Context context) {
			this.context = context;
		}

		@Override
		public void run() {
			super.run();
			try {
				if (os != null && is != null) {
					os.write(preCommand);
					new SendCommandThread().start();
					receiverMachCode(); // 获取供包台的编号
					readBluetoothData(); // 获得供包台返回的数据
				}
			} catch (Exception e) {
				ExceptionLog.writeLog(
						"MeasureArrivePieceBeforeActivity.ReadThread",
						e.getMessage());
				isFinish = true;
				closeBluetoothSocket();
				System.out.println("出异常了。。。。" + e.getMessage());
				e.printStackTrace();
			}
		}

		private void readBluetoothData() throws IOException {
			byte[] buffer = new byte[14];
			byte[] receiveBuffer = new byte[14];
			int length = 0;
			int dpr = 0;
			int sum = 0;
			while (!isFinish) {
				// 报文数据起始标志
				try {
					length = is.read(buffer);
				} catch (Exception e) {
					e.printStackTrace();
				}
				for (int i = 0; i < length; i++) {
					if ((dpr + i) < 14) {
						receiveBuffer[dpr + i] = buffer[i];
						sum++;
					} else {
						sum = 0;
						dpr = 0;
					}
				}
				dpr = dpr + length;
				if (sum == 14) {
					sum = 0;
					dpr = 0;
					// 比较校验位
					int check = 0;
					for (int i = 1; i < 12; i++) {
						check += receiveBuffer[i];
					}
					if ((check & 0xff) == (int) (receiveBuffer[12] & 0xff)
							&& receiveBuffer[13] == 0x2A
							&& receiveBuffer[0] == 0x40) {

						// sendReceiveCommand();
						parserData(receiveBuffer);
					} else {
						System.out.println("执行 错误数据2");
						receiveBuffer = new byte[14];
					}
				} else if ((sum > 0 && sum < 14)
						&& (receiveBuffer[0] != 0x40 || receiveBuffer[dpr - 1] == 0x2A)) {
					System.out.println("执行 错误数据1  dpr：" + dpr);
					sum = 0;
					dpr = 0;
					buffer = new byte[14];
					receiveBuffer = new byte[14];
				}

			}

		}

		// private void sendReceiveCommand() throws IOException {
		// if (os != null && is != null) {
		// os.write(getbytes());
		// os.flush();
		// }
		//
		// }

		// private byte[] getbytes() {
		// String randomCode = RandomUtil.getRandomNumbers(12);
		// ExceptionLog.writeLog(
		// "MeasureArrivePieceBeforeActivity randomCode", randomCode);
		// randomCode = "ADD," + randomCode;
		// byte[] bs = new byte[18];
		// bs[0] = 0x02;
		// bs[17] = 0x03;
		// String ss = "2";
		// int i = 1;
		// for (byte t : randomCode.getBytes()) {
		// bs[i] = t;
		// i++;
		// ss = ss + "," + t;
		// }
		// ss = ss + "3";
		// ExceptionLog.writeLog("MeasureArrivePieceBeforeActivity bs", ss);
		// return bs;
		// }

		private void parserData(byte[] buf) {
			int[] saveData = new int[5];
			// 解析长 宽 高 重量 体积
			if (saveData != null) {
				System.out.println("获取长宽高");
				saveData[0] = buf[4] & 0xff;
				saveData[1] = buf[5] & 0xff;
				saveData[2] = buf[6] & 0xff;
				saveData[3] = (buf[7] & 0xff) << 8 | (buf[8] & 0xff);
				saveData[4] = (buf[9] & 0xff) << 16 | (buf[10] & 0xff) << 8
						| (buf[11] & 0xff);
				Message msg = jHandler.obtainMessage();
				JipaoqiDataEntity ji = new JipaoqiDataEntity();
				ji.lenght = saveData[0];
				ji.wide = saveData[1];
				ji.high = saveData[2];
				ji.weight = dealWeight((float) saveData[3]);
				ji.volume = saveData[4];
				ji.jipaoqiTypeCode = machineCode;
				msg.what = BLUETOOTH_DATA_WHTA;
				msg.obj = ji;
				jHandler.sendMessage(msg);
			}
		}

		// 精确小数位
		private String dealWeight(float weight) {

			String retWeight = "0.0", weightStr = "0.0";
			try {
				weight = weight / 1000;
				weightStr = String.valueOf(weight);
				String str[] = weightStr.split("\\.");
				if (str.length > 1) {
					// 小数点一位
					if (decimalPlaces.equals(context
							.getString(R.string.decimal_places_one))) {
						if (str[1].length() >= 2) {
							str[1] = str[1].substring(0, 1);
						}
					}
					// 小数点二位
					else if (decimalPlaces.equals(context
							.getString(R.string.decimal_places_two))) {
						if (str[1].length() >= 3) {
							str[1] = str[1].substring(0, 2);
						}
					}
					// 小数点三位
					else if (decimalPlaces.equals(context
							.getString(R.string.decimal_places_three))) {
						if (str[1].length() >= 4) {
							str[1] = str[1].substring(0, 3);
						}
					}
				} else {
					return weightStr;
				}
				retWeight = str[0] + "." + str[1];
			} catch (Exception e) {
				e.printStackTrace();

			}
			return retWeight;
		}

		private void receiverMachCode() throws IOException {
			byte[] buffer = new byte[14];
			byte[] receiveBuffer = new byte[14];
			int length = 0;
			int dpr = 0;
			int sum = 0;
			// 第一次读取后置前置协议回复
			while (!isFinish) {
				try {
					length = is.read(buffer);
				} catch (Exception e) {
					e.printStackTrace();
				}
				for (int i = 0; i < length; i++) {
					if ((dpr + i) < 14) {
						receiveBuffer[dpr + i] = buffer[i];
						sum++;
					} else {
						sum = 0;
						dpr = 0;
					}
				}
				System.out.println("获取回复协议： " + Arrays.toString(receiveBuffer));
				dpr = dpr + length;
				if (sum > 10) {
					sum = 0;
					dpr = 0;
					if (receiveBuffer[0] == 0x40) {
						if (receiveBuffer[10] == 0x2A) {
							saveMachCode(receiveBuffer);
						}
						if (receiveBuffer[13] == 0x2A) {
							parserData(receiveBuffer);
						}
						System.out.println("break");
						break;
					}
				}
			}
		}
	}

	private void saveMachCode(byte[] buf) {
		companyMachCode = new int[5];
		companyMachCode[0] = buf[4] & 0xff;
		companyMachCode[1] = buf[5] & 0xff;
		companyMachCode[2] = buf[6] & 0xff;
		companyMachCode[3] = buf[7] & 0xff;
		companyMachCode[4] = buf[8] & 0xff;
		StringBuilder companyCode = new StringBuilder();
		for (int i = 0; i < companyMachCode.length; i++) {
			companyCode.append(companyMachCode[i]);
		}
		machineCode = companyCode.toString();
	}

	private void closeBluetoothSocket() {
		if (bearingBlueThread != null) {
			bearingBlueThread.cancel();
			bearingBlueThread = null;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		isFinish = true;
		closeBluetoothSocket();
	}

	@Override
	public void onBackPressed() {
		showNotice();
	}

	@Override
	protected void handlerScanData(String scanData) {
		if (!code.isEnabled())
			return;
		if (CheckScanCode(scanData)) {
			code.setText(scanData);
			Helper.showSoundAndVibrator(this, true);
			processScanData();
		} else {
			ScanOpen();
		}
	}

	private void doSave(JipaoqiDataEntity data) {
		if (addPieceRecord(data)) {
			this.addCodeNumber();
			setSaveData(true);
			SoundManager.getInstance(
					MeasureArrivePieceBeforeActivity.this)
					.playWeightSound();
			Helper.vibratorToast(this, 100);

			addScanRecordInfo(code.getText().toString(), data);
		} else {
			Helper.showSoundToast(this, getString(R.string.code_repeat), false);
		}
		code.setText("");

	}


	@SuppressLint("NewApi")
	private void processScanData() {

		sendCommand();
		Helper.showCanHideToast(this, "正在获取重量...", Toast.LENGTH_SHORT);

	}

	// 增加一条记录
	private boolean addPieceRecord(JipaoqiDataEntity data) {
		boolean ret;

		dataBusiness.initInsertData();
		// 扫描类型
		dataBusiness
				.setCommand_type(EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE
						.getOpCode());
		// 单号
		dataBusiness.setBar_code_number(code.getText().toString());
		dataBusiness.setCodeType(getExpType(code.getText().toString()));

		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());
		// 工号
		dataBusiness.setJob_number(StoFilePreference.getInstance(this)
				.getUserCode());


		dataBusiness.setExpress_type("5");
		dataBusiness.setFunction_type("1");
		// 插入数据
		ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
				EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE);
		if (!ret && !("").equals(dataBusiness.getWeight())) {
			ret = StoDataBaseOperation.getInstance(this).replace(dataBusiness,
					EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE);
			if (ret) {
				removeItem(code.getText().toString(), 1);
			}
		}
		return ret;
	}

	private boolean CheckScanCode(String code) {
		boolean ret = false;
		EnumScanCode status = ProcessScanCode.getInstance(this)
				.ScanCodeResolve(code,
						EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE);

		switch (status) {
		// 条码空
		case CODE_EMPTY:
			Helper.showSoundToast(this, getString(R.string.code_empty), false);
			break;

		// 非法条码
		case CODE_ILLEGAL:
			Helper.showSoundToast(this, getString(R.string.error_code), false);
			break;
		// 成功条码
		case CODE_WAY_BILL:
			ret = true;
			break;
		default:
			break;
		}

		return ret;
	}
}
